/**
 * 
 * 广州锐鹏计算机科技有限公司（www.ruipengkj.com）
 * 
 * 
 * Copyright (c) 2011-2012 RUIPENGKJ.Co.Ltd. All rights reserved.
 * 
 * */
package com.ruipengkj.view.orderView;
/**
 * 说明：
 * 销售退货单
 * @Author：黄盛强
 * @Date：2012-03-20
 */	
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.Date;
import java.util.List;

import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableCellEditor;

import com.ruipengkj.ApplicationContext;
import com.ruipengkj.bean.TBillDetail;
import com.ruipengkj.bean.TOrder;
import com.ruipengkj.bean.TOrderReturn;
import com.ruipengkj.bean.TStore;
import com.ruipengkj.bean.TUser;
import com.ruipengkj.commons.BuildSpringApplication;
import com.ruipengkj.commons.util.IDNameBean;
import com.ruipengkj.commons.util.TabelUtil;
import com.ruipengkj.commons.util.UUID;
import com.ruipengkj.commons.util.Util;
import com.ruipengkj.component.JComboBoxPOJO;
import com.ruipengkj.component.JLabelJComboBoxComponent;
import com.ruipengkj.component.JLabelJTextFieldComponent;
import com.ruipengkj.component.RPJButtonRoundBlue;
import com.ruipengkj.component.RPJButtonRoundOrager;
import com.ruipengkj.component.RPJButtonWhite;
import com.ruipengkj.component.comboBox.CommodityJComboBoxTableSales;
import com.ruipengkj.component.jdialog.BorderJPanel;
import com.ruipengkj.component.jdialog.IDialog;
import com.ruipengkj.component.jpanel.RepeatImagePanel;
import com.ruipengkj.factory.ImageFactory;
import com.ruipengkj.model.OrderReturnDetailModel;
import com.ruipengkj.service.TBillDetailService;
import com.ruipengkj.service.TCommodityService;
import com.ruipengkj.service.TOrderReturnService;
import com.ruipengkj.service.TOrderService;
import com.ruipengkj.service.TStoreService;
import com.ruipengkj.service.TUserService;
	
public class MarketReturnedAddOrModifyDialog extends IDialog implements TableModelListener {
	
	private static final long serialVersionUID = 1L;
	private JLabelJComboBoxComponent storeBox = null;//仓库
	private JLabelJComboBoxComponent returnPeople = null;//退货人
	private JLabelJTextFieldComponent returnID;//退货单编号
	private JLabelJTextFieldComponent returnedCause = null;//退货原因
	private JLabelJTextFieldComponent numTF;//数量
	private JLabelJTextFieldComponent moneyTF;//金额
	private JLabelJTextFieldComponent storageQuantityTF;//存库量
	
	private JButton saveExitButton; //保存退出
	private JButton saveButton; //保存新增
	private JButton exitButton; //直接退出
	private JButton addButton;//添加行
	private JButton delButton;//删除行
	
	private JTable table;
	private JScrollPane tableJsp;
	private OrderReturnDetailModel orderReturnDetailModel;
	
	private TOrderService tOrderService;//订单
	private TBillDetailService billDetailService;//订单详细操作对象
	private TStoreService tStoreService;//仓库操作对象
	private TOrderReturnService tOrderReturnService;//销售退货操作对象
	private TCommodityService tCommodityService;//商品
	private TUserService tUserService;//会员
	public boolean isSuccess=false;
	private TOrderReturn tOrderReturn;
	public MarketReturnedAddOrModifyDialog(JDialog jd, String title, boolean b) {
		super(jd, "销售退货", b);
		tOrderService = BuildSpringApplication.getInstance().getTOrderServiceImpl();
		billDetailService=BuildSpringApplication.getInstance().getTBillDetailServiceImpl();
		tStoreService=BuildSpringApplication.getInstance().getTStoreServiceImpl();
		tOrderReturnService=BuildSpringApplication.getInstance().getTOrderReturnServiceImpl();
		tUserService=BuildSpringApplication.getInstance().getTUserServiceImpl();
		tCommodityService=BuildSpringApplication.getInstance().getTCommodityServiceImpl();
		this.init();
		this.initListener();
		this.setSize(850, 550);
		this.setLocationRelativeTo(null);
	}
	
	private void init() {
		orderReturnDetailModel = new OrderReturnDetailModel();
		table=uiFactory.createRPJTable(orderReturnDetailModel, this, this, 30, JLabel.CENTER);
		CommodityJComboBoxTableSales cbox = new CommodityJComboBoxTableSales();
		cbox.setBorder(null);
		TableCellEditor edt = new DefaultCellEditor(cbox);
		table.getColumnModel().getColumn(2).setCellEditor(edt);
		table.getColumnModel().getColumn(3).setCellEditor(edt);
		tableJsp=uiFactory.createJScrollPane(table);
		
		TabelUtil.hideTableColumn(0, table);
		
		JPanel main_jp=new BorderJPanel(new BorderLayout());
		main_jp.setBackground(Color.white);
		main_jp.setBackground(Util.PANEL_COLOR);
		main_jp.add(this.initTop(), BorderLayout.NORTH);
		main_jp.add(tableJsp, BorderLayout.CENTER);
		main_jp.add(this.initTail(), BorderLayout.SOUTH);
		this.add(main_jp);
		main_jp.setCursor(Util.CURSOR_DEFAULT);
	}
	
	private JPanel initTop() {
		
		JPanel jp1 = uiFactory.createFlowJPanel(FlowLayout.LEFT);
		storeBox= new JLabelJComboBoxComponent("退货仓库：", new String[]{});
		storeBox.addElement(new JComboBoxPOJO("请选择"));
		returnPeople = new JLabelJComboBoxComponent("退 货 人：", new String[]{},180);
		returnPeople.addElement(new IDNameBean("0", "请选择"));
		returnID = new JLabelJTextFieldComponent("退货单编号：", 30);
		returnID.getText().setEditable(false);
		returnID.getText().setText(UUID.GenUUID15());
		jp1.add(storeBox);
		jp1.add(returnPeople);
		jp1.add(returnID);
		
		JPanel jp2 = uiFactory.createFlowJPanel(FlowLayout.LEFT);
		JLabelJTextFieldComponent operator =new JLabelJTextFieldComponent("操 作 人：",30);
		operator.getText().setText(ApplicationContext.OPERATOR_NAME);
		operator.getText().setEditable(false);
		returnedCause = new JLabelJTextFieldComponent("退货原因：", 40);
		jp2.add(operator);
		jp2.add(returnedCause);
		
		
		JPanel top_panel = new RepeatImagePanel(ImageFactory.loadImage(ImageFactory.DIALOG_TOP_BG_2).getImage());
		top_panel.setLayout(new GridLayout(2, 1));
		top_panel.add(jp1);
		top_panel.add(jp2);
		return top_panel;
	}
	
	private JPanel initTail() {
		JPanel tail_panel = new RepeatImagePanel(ImageFactory.loadImage(ImageFactory.DIALOG_TOP_BG_2).getImage());
		tail_panel.setLayout(new GridLayout(2, 1));
		
		JPanel jp8 = uiFactory.createFlowJPanel(FlowLayout.LEFT);
		addButton = new RPJButtonRoundBlue("添加行");
		delButton = new RPJButtonRoundOrager("删除行");
		jp8.add(addButton);
		jp8.add(delButton);
		
		JPanel jp1 = uiFactory.createFlowJPanel(FlowLayout.LEFT);
		numTF = new JLabelJTextFieldComponent("合计：数量", 10);
		numTF.getText().setText("0");
		numTF.getText().setEditable(false);
		moneyTF = new JLabelJTextFieldComponent("金额：", 10);
		moneyTF.getText().setText("0.0");
		moneyTF.getText().setEditable(false);
		storageQuantityTF = new JLabelJTextFieldComponent("当前库存量：", 10);
		storageQuantityTF.getText().setText("0");
		storageQuantityTF.getText().setEditable(false);
		jp1.add(numTF);
		jp1.add(moneyTF);
		jp1.add(storageQuantityTF);
		
		saveExitButton = new RPJButtonWhite("保存退出(Ctrl+S)");
		saveButton = new RPJButtonWhite("保存新增(Ctrl+I)");
		exitButton = new RPJButtonWhite("直接退出(Ctrl+Q)");
		jp1.add(saveExitButton);
		jp1.add(saveButton);
		jp1.add(exitButton);
		
		tail_panel.add(jp8);
		tail_panel.add(jp1);
		return tail_panel;
	}
	
	private void initListener(){
		storeBox.getBox().addActionListener(this);
		addButton.addActionListener(this);
		delButton.addActionListener(this);
		saveExitButton.addActionListener(this); //保存退出
		saveExitButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_I, KeyEvent.CTRL_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW);
		saveButton.addActionListener(this); //保存新增
		saveButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW);
		exitButton.addActionListener(this); //直接退出
		exitButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_Q, KeyEvent.CTRL_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW);
		orderReturnDetailModel.addTableModelListener(this);
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource()==addButton){
			//添加行
			if(storeBox.getBox().getSelectedIndex()==0){
				JOptionPane.showMessageDialog(null, "请选择退货仓库");
				storeBox.getBox().requestFocus();
				return;
			}
//			if(returnPeople.getBox().getSelectedIndex()==0){
//				JOptionPane.showMessageDialog(null, "请选择退货人");
//				returnPeople.getBox().requestFocus();
//				return;
//			}
			TBillDetail detail=new TBillDetail();
			detail.setDetailID(UUID.GenUUID15());
			detail.setBillID(returnID.getText().getText().trim());
			detail.setDiscountID("");
			detail.setNum(1);
			detail.setBillType(ApplicationContext.BILL_BILLTYPE4);
			orderReturnDetailModel.addBillDetail(detail);
		}else if(e.getSource()==delButton){
			//删除行
			int row=table.getSelectedRow();
			if(row!=-1){
				if(Util.showConfirmDialog("是否要删除选中行？")==0){
					orderReturnDetailModel.delBillDetail(row);
				}
			}
		}else if(e.getSource()==saveExitButton){
			//保存退出
			if(this.addOrderReturn()){
				this.dispose();
			}
		}else if(e.getSource()==saveButton){
			//保存新增
			if(this.addOrderReturn()){
				returnID.getText().setText(UUID.GenUUID15());//退货单编号
				returnPeople.getBox().setSelectedIndex(1);//退 货 人;
				returnedCause.getText().setText("");//退货原因
				orderReturnDetailModel.clearAllBillDetail();
				table.updateUI();
			}
		}else if(e.getSource()==exitButton){
			//直接退出
			if(Util.showConfirmDialog("是否要退出？")==0){
				this.dispose();
			}
		} else if (e.getSource() == storeBox.getBox()) {
			//切换仓库
			count();
		} else {
			super.actionPerformed(e);
		}
	}
	
	@Override
	public void mouseClicked(MouseEvent e) {
		if (e.getSource() == table) {
			this.count();
		}
	}
	private  boolean addOrderReturn(){
		String returnIDStr = returnID.getText().getText().trim();//退货单编号
		String returnedCauseStr =returnedCause.getText().getText().trim();//退货原因
		if(returnedCauseStr.length()>512){
			JOptionPane.showMessageDialog(null, "退货原因不能大于512个字");
			returnedCause.getText().requestFocus();
			return false;
		}
//		if(returnPeople.getBox().getSelectedIndex()==0){
//			JOptionPane.showMessageDialog(null, "请选择退货人");
//			returnPeople.getBox().requestFocus();
//			return false;
//		}
		if(storeBox.getBox().getSelectedIndex()==0){
			JOptionPane.showMessageDialog(null, "请选择退货仓库");
			storeBox.getBox().requestFocus();
			return false;
		}
		List<TBillDetail> billDetailList=orderReturnDetailModel.findAllBillDetailList();
		if(billDetailList==null||billDetailList.size()==0){
			JOptionPane.showMessageDialog(null, "请先添加商品");
			return false;
		}
		
		//获取用户
		IDNameBean IDNameBean = (IDNameBean)returnPeople.getBox().getSelectedItem();
		TUser tUser = new TUser(IDNameBean.getStrId());
		//根据用户查询订单
		TOrder tOrder = new TOrder();
		tOrder.setTUser(tUser);
		List<TOrder> tOrderList = null;
		try {
			tOrderList = tOrderService.findService(tOrder);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		boolean okNull = false;//记录是否允许价格为空，放置消息框无限弹出
		for(int i=0;i<billDetailList.size();i++){
			TBillDetail tBillDetail = billDetailList.get(i);
//			if ()
			if (tBillDetail.getCommodityID().length() == 0) {
				JOptionPane.showMessageDialog(null, "存在商品编号为空的商品！");
				return false;
			}
			if (tBillDetail.getNum() == 0) {
				JOptionPane.showMessageDialog(null, "存在商品数量为0的商品！");
				return false;
			}
			
			if (tBillDetail.getPrice() <= 0 && !okNull) {
				if(Util.showConfirmDialog("允许商品的价格不大于零？")!=0) {
					return false;
				} else {
					okNull = true;
				}
			}
			
		}
		String beanID = null;
		if (returnPeople.getBox().getSelectedIndex() != 0) {
			IDNameBean bean=(IDNameBean)returnPeople.getBox().getSelectedItem();//退货人
			beanID = bean.getStrId();
		}
		JComboBoxPOJO storePO=(JComboBoxPOJO)storeBox.getBox().getSelectedItem();
		TStore store=(TStore)storePO.getObject();
		
		TOrderReturn orderReturn=new TOrderReturn();
		orderReturn.setReturnID(returnIDStr);//退货编号CHAR(15) PK
		orderReturn.setReason(returnedCauseStr);//退货原因VARCHAR(512)
		orderReturn.setOperator(ApplicationContext.OPERATOR_ID);//操作人CHAR(15)
		orderReturn.setHappenTime(new Date());//操作时间DATETIME
		orderReturn.setRelOrderID("");//原相关订单CHAR(15)
		orderReturn.setStoreName(store.getName());
		if (beanID != null && !beanID.equals(""))
		orderReturn.setTUser(new TUser(beanID));//用户
		try {
			tOrderReturnService.saveService(orderReturn);
			List<TBillDetail> list = orderReturnDetailModel.findAllBillDetailList();
			ApplicationContext.addInOutBillDetailMoney(list,(TStore)storePO.getObject(),ApplicationContext.STOCK_IN_OUT_SOURCE_TYPE4,ApplicationContext.STOCK_TYPE_IN,returnID.getText().getText().trim(),ApplicationContext.MONEYINOUT_TYPE_OUT,ApplicationContext.MONEYINOUT_SOURCE_TYPE4,beanID);
			ApplicationContext.TCommodityAvgPrice(list);
			this.isSuccess=true;
			BuildSpringApplication.getInstance().getTOpLogServiceImpl().addOpLogService("添加销售退货单信息");
			JOptionPane.showMessageDialog(null, "操作成功");
			return true;
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, "操作失败");
			e.printStackTrace();
			this.isSuccess=false;
			return false;
		}
	}
	public void showDialog(String id) {
		try {
			if (id != null && !id.equals("")){
				tOrderReturn = tOrderReturnService.getByIdService(id);
			}
			this.showDialog(tOrderReturn);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//显示窗体
	private void showDialog(TOrderReturn orderReturn){
		this.isSuccess=false;
		if(orderReturn!=null){
			returnID.getText().setText(orderReturn.getReturnID());//退货单编号
			returnedCause.getText().setText(orderReturn.getReason());//退货原因
//			storeBox.addElement(new JComboBoxPOJO(orderReturn.getStoreName()));
			addButton.setEnabled(false);
			delButton.setEnabled(false);
			saveButton.setEnabled(false);
			saveExitButton.setEnabled(false);
			SwingUtilities.invokeLater(queryBillDetail);
		}
		SwingUtilities.invokeLater(queryStore);
		SwingUtilities.invokeLater(queryUser);
		this.setVisible(true);
	}
	//查询仓库
	private Runnable queryStore=new Runnable() {
		@Override
		public void run() {
			try {
				storeBox.getModel().removeAllElements();
				storeBox.addElement("请选择仓库");
				List<TStore> list=tStoreService.findService(null);
				if(list!=null&&list.size()!=0){
					for(int i=0;i<list.size();i++){
						TStore store=list.get(i);
						storeBox.addElement(new JComboBoxPOJO(store.getStoreID(),store.getName(),store));
						if(tOrderReturn!=null&&tOrderReturn.getStoreName()!=null&&!tOrderReturn.getStoreName().equals("")){
							storeBox.getBox().setSelectedIndex(i);
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};
	//查询详细
	public Runnable queryBillDetail=new Runnable(){
		@Override
		public void run() {
			TBillDetail tBillDetail = new TBillDetail();
			tBillDetail.setBillID(returnID.getText().getText().trim());
			tBillDetail.setBillType(ApplicationContext.BILL_BILLTYPE4);
			try {
				List<TBillDetail> billDetailList = billDetailService.findService(tBillDetail);
				if(billDetailList!=null&&billDetailList.size()!=0){
					int length = billDetailList.size();
					for (int i = 0; i < length; ++i) {
						//获取商品 以便查看
						billDetailList.get(i).setCommodity(tCommodityService.getByIdService(billDetailList.get(i).getCommodityID()));
						orderReturnDetailModel.addBillDetail(billDetailList.get(i));
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};
	//读取退货人
	public Runnable queryUser=new Runnable() {
		@Override
		public void run() {
			try {
				List<TUser> list=tUserService.findService(null);
				if(list!=null&&list.size()!=0){
					for(int i=0;i<list.size();i++){
						TUser emp=list.get(i);
						returnPeople.addElement(new IDNameBean(emp.getUserID(), emp.getUserName()));
						if(tOrderReturn!=null){
							TUser user=tOrderReturn.getTUser();
							if(user!=null){
								if(emp.getUserID().equals(user.getUserID())){
									returnPeople.getBox().setSelectedIndex(i+1);//退货人
								}
							}
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};
	
	private void count() {
		int row=table.getSelectedRow();
		if(row!=-1 && row < orderReturnDetailModel.getRowCount()){
			Object obj=table.getValueAt(row, 2);
			if(obj!=null && storeBox.getBox().getSelectedIndex() > 0){
				JComboBoxPOJO storePO=(JComboBoxPOJO)storeBox.getBox().getSelectedItem();
				ApplicationContext.countStoreNumber(orderReturnDetailModel.findAllBillDetailList(), (TStore)storePO.getObject(), obj.toString(), numTF.getText(), moneyTF.getText(), storageQuantityTF.getText());
			}
		}
	}
	
	@Override
	public void tableChanged(TableModelEvent arg0) {
		count();
	}
	
	public static void main(String[] args) {
		MarketReturnedAddOrModifyDialog dialog = new MarketReturnedAddOrModifyDialog(null, "添加部门", true);
		dialog.setVisible(true);
	}
}
